package org.geektimes.juc;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @FileName: JucTest1
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2021/3/30 - 上午12:51
 */
@Deprecated
public class JucTest1 {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            String threadName = "线程" + i;
            new Thread(new MyThread(latch), threadName).start();
        }
        System.out.println("等待所有线程准备结束...");
        latch.await();
        System.out.println("所有线程结束,程序终止");
    }

    static class MyThread implements Runnable {

        private CountDownLatch latch;

        public MyThread(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override
        public void run() {
            Random random = new Random();
            int i = random.nextInt(5) + 1;
            try {
                TimeUnit.SECONDS.sleep(i);
                System.out.printf("线程: %s, 休眠了 %d 秒.... \n", Thread.currentThread().getName(), i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }
    }
}
